package com.gobuy.system.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gobuy.system.utils.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Gaozexi on 2020/6/8 21:40
 * Step by Step  and Stand on,  You Are The Best Investment!
 * TODO 待优化, 用 config配置中心 实现 热配置
 */
@Component
public class IpConfigListener implements ApplicationRunner {
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${domain-name}")
    private  String domainName;

    @Value("${ip-address}")
    private  String ipAddress;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        ObjectMapper objectMapper =new ObjectMapper();
        String[] domainNames = domainName.split(",");
        String[] ipInfos = ipAddress.split(",");
        List<String> domainList = Arrays.asList(domainNames);
        for (String domainName : domainList) {
            List<String> ips = IpUtil.getAllIPByName(domainName);
             String ipJsons = objectMapper.writeValueAsString(ips);
            redisTemplate.opsForHash().put("black-ip-items",domainName,ipJsons);
        }
        List<String> list =new ArrayList<String>();
        for (String ipInfo : ipInfos) {
            list.add(ipInfo);
        }
        redisTemplate.opsForHash().put("black-ip-items","unknown-domain",
                objectMapper.writeValueAsString(list));

    }
}
